<script setup lang="ts">

import {EditPen, Lock, Message, UserFilled} from "@element-plus/icons-vue";
import {ref, computed, reactive,onUnmounted,onMounted} from 'vue'
import {sendEmail, UserRegister} from "@/netForAxios/net";
import {ElMessage} from "element-plus";
import router from "@/router";

const form = reactive({
  username: "",
  password: "",
  password_confirmation: "",
  email: "",
  code: ""
})
const formCheck = ref();

const validateUsername = (rule, value, callback) => {
  if (value == '') {
    callback(new Error("Username is required"));
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error("Usernames cannot contain special characters!"));
  } else {
    callback()
  }
}

const validatePasswordConfirm = (rule, value, callback) => {
  if (value == '') {
    callback(new Error("Password is required"));
  } else if (value != form.password) {
    callback(new Error("Password is not same!"));
  } else {
    callback()
  }
}
const rule = {
  username: [{
    validator: validateUsername,
    trigger: ['blur', 'change'],
  }],
  password: [{
    required: true, message: 'please enter your password', trigger: 'blur'
  }, {
    min: 6, max: 20, message: 'Passwords are between six and twenty in length', trigger: ['blur', 'change']
  }],
  password_confirmation: [{
    validator: validatePasswordConfirm,
    trigger: ['blur', 'change']
  }],
  email: [{
    required: true, message: 'please enter your email', trigger: 'blur'
  }, {
    type: 'email', message: 'Please enter truth email address', trigger: ['blur', 'change']
  }],
  code: [{
    required: true, message: 'please enter code', trigger: 'blur'
  }]
}
// 倒计时时间（秒）
const countdown = ref(0);
// 是否正在发送
const isSending = ref(false);
let timer = null;

// 计算属性：按钮是否禁用
const isDisabled = computed(() => {
  return countdown.value > 0 || isSending.value;
});

// 计算属性：按钮文本
const buttonText = computed(() => {
  if (isSending.value) {
    return 'sending...';
  } else if (countdown.value > 0) {
    return `resend(${countdown.value}s)`;
  } else {
    return 'send';
  }
});
const sendCode = async () => {
  if (isDisabled.value) return;

  isSending.value = true;
  try {
    if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
      sendEmail(form.email, () => {
        countdown.value = 0;
        return;
      })
    } else {
      ElMessage.warning("Please enter a valid email address!");
      return;
    }
    //定时器清除
    if (timer) clearTimeout(timer);
    // 开始倒计时
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        countdown.value = 0;
      }
      localStorage.setItem("countdownTime",  JSON.stringify(countdown.value));
    }, 1000);

  } catch (err) {

  } finally {
    isSending.value = false;
  }
}
onMounted(()=>{
  const saved = localStorage.getItem('countdownTime')
  if (saved) {
    countdown.value = JSON.parse(saved);
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        countdown.value = 0;
      }
      localStorage.setItem("countdownTime",  JSON.stringify(countdown.value));
  },1000)
  }
});
onUnmounted(() => {
  if (timer) clearTimeout(timer)
});

function registered() {
  formCheck.value.validate(async (valid) => {
    if (valid) {
      UserRegister(form.username, form.password, form.email, form.code, () => {
        router.push('/');
      })
    }
  })
}
</script>

<template>
  <div class="register-box">
    <h1>Register</h1>
    <div class="register-form">
      <el-form :model="form" :rules="rule" ref="formCheck">
        <el-form-item prop="username">
          <el-input v-model="form.username" maxlength="10" type="text" placeholder="Username">
            <template #prefix>
              <el-icon>
                <UserFilled/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" maxlength="20" type="password" placeholder="Password">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password_confirmation">
          <el-input v-model="form.password_confirmation" maxlength="20" type="password" placeholder="confirmPassword">
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" maxlength="35" type="text" placeholder="email@.com">
            <template #prefix>
              <el-icon>
                <Message/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="code">
              <el-input v-model="form.code" maxlength="6" type="text" placeholder="xxxxxx">
                <template #prefix>
                  <el-icon>
                    <EditPen/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button :loading="isSending" :disabled="isDisabled" @click="sendCode" type="primary" style="
            width: 50%;
            text-align: right" plain>{{ buttonText }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-button @click="registered" style="margin-top: 50px; height: 40px;width: 90%;" type="success">registered
      </el-button>
    </div>
    <div style="margin-top: 20px">
      <span style="line-height: 15px;font-size: 14px;color: rgba(196,196,196,0.8);font-weight: bold">Already have an account? </span>
      <el-link style="translate: 0 -2px;font-weight: bold" type="primary" @click="$router.push('/')">login now!
      </el-link>
    </div>
  </div>

</template>

<style scoped>
.register-box {
  text-align: center;
}

.register-box h1 {
  margin-top: 50px;
  letter-spacing: 5px;
  text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
  color: white;
  text-align: center;
}

.register-form {
  width: 60%;
  margin: 50px auto 20px;
}


</style>